package com.xc.hotelmgr.order.modules.ali.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.xc.hotelmgr.order.common.utils.*;
import com.xc.hotelmgr.order.modules.ali.service.ReceOrdeService;
import com.xc.hotelmgr.order.modules.ali.to.orderrefundrq.request.OrderRefundRQ;
import com.xc.hotelmgr.order.modules.ali.to.bookrq.request.*;
import com.xc.hotelmgr.order.modules.ali.to.bookrq.response.BookRQResult;
import com.xc.hotelmgr.order.modules.ali.to.cancelrq.CancelRQ;
import com.xc.hotelmgr.order.modules.ali.to.cancelrq.CancelRQResult;
import com.xc.hotelmgr.order.modules.ali.to.manuorder.ManuBookRQ;
import com.xc.hotelmgr.order.modules.ali.to.paysuccessrq.request.PaySuccess;
import com.xc.hotelmgr.order.modules.ali.to.paysuccessrq.response.PaySuccessResult;
import com.xc.hotelmgr.order.modules.ali.to.querystatusrq.request.QueryStatusRQRequest;
import com.xc.hotelmgr.order.modules.ali.to.querystatusrq.response.QueryStatusRQResult;
import com.xc.hotelmgr.order.modules.ali.to.validaterq.request.ValidateRQ;
import com.xc.hotelmgr.order.modules.ali.to.validaterq.response.ValidateRQResult;
import com.xc.hotelmgr.order.modules.ctrip.service.CtripOrderService;
import com.xc.hotelmgr.order.modules.ctrip.service.CtripValidateService;
import com.xc.hotelmgr.order.modules.mt.service.MtOrderService;
import com.xc.hotelmgr.order.modules.mt.service.MtHotelOrderCheckService;
import com.xc.hotelmgr.order.modules.order.entity.*;
import com.xc.hotelmgr.order.modules.order.service.*;
import com.xc.hotelmgr.order.modules.ali.to.common.DailyInfo;
import com.xc.hotelmgr.order.modules.yd.service.YdValidateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service("orderServiceImpl")
@Slf4j
public class ReceOrdeServiceImpl implements ReceOrdeService {
    @Autowired
    DtStoreService dtStoreService;

    @Autowired
    private DtOrderChannelsService dtOrderChannelsService;


    @Autowired
    private OrderService orderService;

    @Autowired
    private DailyInfoService dailyInfoService;

    @Autowired
    private DailyOriInfoService dailyOriInfoService;

    @Autowired
    private DailyDisInfoService dailyDisInfoService;

    @Autowired
    private GuestService guestService;

    @Autowired
    private InvoiceInfoService invoiceInfoService;

    @Autowired
    private VoucherinfoService voucherinfoService;

    @Autowired
    private TravelInfoService travelInfoService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private PackService packService;

    @Autowired
    private PackInfoService packInfoService;

    @Autowired
    private CtripOrderService ctripOrderService;

    @Autowired
    private CtripValidateService ctripValidateService;

    @Autowired
    private MtHotelOrderCheckService mtValidateService;

    @Autowired
    private MtOrderService mtOrderService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private YdValidateService ydValidateService;

    @Override
    public String router(String xml) throws DocumentException, InterruptedException {
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();
        String rootName = root.getName();
        Element authNode=root.element("AuthenticationToken");
        String username = authNode.element("Username").getStringValue();
        String password = authNode.element("Password").getStringValue();
        String result = "";
        //权限验证
        Integer count = dtStoreService.getBaseMapper().selectCount(new QueryWrapper<DtStoreEntity>().eq("ali_cb_user",username).eq("ali_cb_user_pass",password));
        if(count <= 0){
            result = "权限验证失败";
            return result;
        }
        Constant.AliOrderRouter aliOrderRouter = Constant.AliOrderRouter.valueOf(rootName);
        switch (aliOrderRouter){
            case ValidateRQ:
                result = validateRQ(xml);
                break;
            case BookRQ:
                result = bookRQ(xml);
                break;
            case PaySuccessRQ:
                result = paySuccessRQ(xml);
                break;
            case QueryStatusRQ:
                result = queryStatusRQ(xml);
                break;
            case OrderRefundRQ:
                result = orderRefundRQ(xml);
                break;
            case CancelRQ:
                result = cancelRQ(xml);
                break;
        }
        return result;
    }

    /**
     * 下单前校验
     * @param xml
     * @return
     */
    @Override
    public String validateRQ(String xml) throws InterruptedException {
        ValidateRQ validateRQ = XmlUtils.fromXML(xml,ValidateRQ.class);
        String rpCode = validateRQ.getRatePlanCode();
        String response = "";
        //自定义价格政策，直接验证通过
        if (StringUtils.contains(rpCode, Constant.ChanelCustomStr)) {
            response = validateRQCustom(validateRQ);
        }else if (StringUtils.contains(rpCode, Constant.ChanelZy)){
            response = validateRQCustom(validateRQ);
        }
        // 携程订单
        else if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelCtrip)){
            response =  ctripValidateService.validateRQ(validateRQ);
        }
        // 美团商旅订单
        else if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelMtBuisness)) {
            // 美团商旅暂未开发
            return response;
        }
        //亚朵订单
        else if (StringUtils.equals(rpCode.substring(0,2),Constant.ChanelYd)){
            return ydValidateService.validateRq(validateRQ);
        }
        // 美团订单，调用美团验证价格接口进行验证
        else {
            response = mtValidateService.validateRQ(validateRQ);
        }

        return response;
    }

    /**
     * 自定义价格政策验单，直接通过
     * @param validateRQ
     * @return
     */
    private String validateRQCustom(com.xc.hotelmgr.order.modules.ali.to.validaterq.request.ValidateRQ validateRQ) {
        List<DailyInfo> dailyInfos = validateRQ.getDailyInfos();
        ValidateRQResult validateRQResponse = GeneValidateVQResponse.gene(true, dailyInfos, "3");
        return XmlUtils.toXML(validateRQResponse);
    }

    /**
     * 预定
     * @param xml
     * @return
     */
    @Override
    public String bookRQ(String xml) {
        BookRQ bookRQ = XmlUtils.fromXML(xml,BookRQ.class);
        String rpCode = bookRQ.getRatePlanCode();
        String hotelId = bookRQ.getHotelId();
        //自有
        if (StringUtils.contains(rpCode,Constant.ChanelZy)){
            BookRQResult bookRQResult = new BookRQResult();
            bookRQResult.setMessage("创建订单成功");
            bookRQResult.setResultCode("0");
            bookRQResult.setOrderId(bookRQ.getTaoBaoOrderId());
            return XmlUtils.toXML(bookRQResult);
        }
        Integer isAuto = dtOrderChannelsService.sqlIsAutoByHotelId(hotelId);
        if (StringUtils.contains(rpCode, Constant.ChanelCustomStr)) {
            rpCode =rpCode.substring(0, rpCode.indexOf("XC"));
            bookRQ.setRatePlanCode(rpCode);
        }
        if(isAuto <= 0){  // isAuto 不等于1 手工订单
           return manualOrder(bookRQ);
        }
        String response = "";

        // 携程订单
        if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelCtrip)){
            String userName = bookRQ.getAuthenticationToken().getUsername();
            DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.sqlSelectKey(Constant.Channel.Ctrip.getValue(), userName);
            OrderEntity orderEntity = saveOrder(bookRQ, Constant.Channel.Ctrip.getValue(), Constant.OrdType.Auto.getValue(),dtOrderChannelsEntity.getDtId(),dtOrderChannelsEntity.getStoreId());
            // 验证价格不通过 人工处理
            if (ratesCheck(orderEntity, 1)) {
                response = toManualOrder(orderEntity);
                log.info("携程验价不通过转人工处理");
                return response;
            }
            response = ctripOrderService.ctripOrder(bookRQ,orderEntity.getId());
        }
        // 美团商旅订单
        else if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelMtBuisness)) {
            // 验证价格不通过 人工处理

            // 暂未开发
        }
        // 美团订单，调用美团下单接口下单
        else {
            String userName = bookRQ.getAuthenticationToken().getUsername();
            DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.sqlSelectKey(Constant.Channel.Mt.getValue(), userName);
            OrderEntity orderEntity = saveOrder(bookRQ, Constant.Channel.Mt.getValue(), Constant.OrdType.Auto.getValue(),dtOrderChannelsEntity.getDtId(),dtOrderChannelsEntity.getStoreId());
            // 验证价格不通过 人工处理
            if (ratesCheck(orderEntity, 2)) {
                log.info("美团验价不通过转人工处理");
                response = toManualOrder(orderEntity);
                return response;
            }
            response = mtOrderService.booking(bookRQ,orderEntity.getId());
        }
        return response;
    }

    /**
     * 价格验证
     * @param orderEntity
     * @return
     */
    private boolean ratesCheck(OrderEntity orderEntity, Integer channel) {
        Integer storeId = orderEntity.getDtStoreId();
        Long rpCode = orderEntity.getRateplanCode();
        int payPrice = 0;
        payPrice = orderEntity.getPayPrice(); // 客人实际支付价格
        DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.getByStoreIdAndChannel(storeId, channel);
        int commRateMt = 0;
        int commRateFz = 0;
        int profitPrice = 0;
        int profitPercent = 0;
        commRateMt = dtOrderChannelsEntity.getCommRate();                  // 美团佣金
        commRateFz = dtOrderChannelsEntity.getCommRateFz();                // 飞猪佣金

        profitPrice = dtOrderChannelsEntity.getProfitPrice();             // 利润容忍固定值
        profitPercent = dtOrderChannelsEntity.getProfitPercent();          // 利润容忍百分比

        Date startDate = orderEntity.getCheckInDate();
        Date endDate = orderEntity.getCheckOutDate();
        Integer dateNum = Integer.valueOf(DateUtils.suDates(endDate, startDate).toString()); // 预定日期跨度
        int buyPrice = 0;                                                      // 数据库价格
        for (int i = 0; i < dateNum; i++) {
            String buyDate = DateUtils.format(DateUtils.addDateDays(startDate, i));
            String result = buyDate.substring(buyDate.length()-5).replace("-","");
            buyPrice += (Integer) redisUtils.hashGet("r" + rpCode + result, "p");
        }
        Integer buyFxMt = (buyPrice*(1000-commRateMt)/1000)*(1000+profitPercent)/1000 + profitPrice;
        Integer buyFxFz = payPrice*(1000-commRateFz)/1000;
        int profit = buyFxFz - buyFxMt;
        return profit < 0;
    }


    /**
     * 前端下单
     * @param manuBookRQ
     */
    @Override
    public R manuBook(ManuBookRQ manuBookRQ) throws InterruptedException {
        String rpCode = manuBookRQ.getRateplanCode().toString();
        //携程订单
        if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelCtrip)){
            return  ctripOrderService.ctripManuOrder(manuBookRQ);
        }
        //美团商旅订单
        else if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelMtBuisness)) {
            // 未开发
            return null;
        }
        // 美团订单，调用美团下单接口下单
        else {
           return mtOrderService.manuBooking(manuBookRQ);
        }
    }

    /**
     * 直连订单转人工订单(修改订单不产生新的订单)
     * @param orderEntity
     * @return
     */
    public String toManualOrder(OrderEntity orderEntity) {
        orderEntity.setOrderType(0);
        orderService.updateById(orderEntity);
        BookRQResult bookRQResult = new BookRQResult();
        bookRQResult.setMessage("创建订单成功");
        bookRQResult.setResultCode("0");
        bookRQResult.setOrderId(orderEntity.getId().toString());
        return XmlUtils.toXML(bookRQResult);
    }

    /**
     * 人工订单（直接产生新的订单）
     * @param bookRQ
     * @return
     */
    private String manualOrder(BookRQ bookRQ){
        BookRQResult bookRQResult = new BookRQResult();
        String rpCode = bookRQ.getRatePlanCode();
        String userName = bookRQ.getAuthenticationToken().getUsername();
        DtStoreEntity dtStoreEntity = dtStoreService.sqlSelectByUserName(userName);
        Constant.Channel channel = null;
        if(dtStoreEntity == null){
            log.error("请配置渠道对应的渠道信息：{}",userName);
        }

        // 美团商旅订单
        if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelMtBuisness)){
            channel = Constant.Channel.MtB;
        }
        // 携程订单
        else if(StringUtils.equals(rpCode.substring(0,2),Constant.ChanelCtrip)){
            channel = Constant.Channel.Ctrip;
        }
        // 美团订单，调用美团下单接口下单
        else {
            channel = Constant.Channel.Mt;
        }
        OrderEntity orderEntity = saveOrder(bookRQ, channel.getValue(), Constant.OrdType.Manu.getValue(),dtStoreEntity.getDtId(),Integer.valueOf(dtStoreEntity.getId().toString()));
        bookRQResult.setMessage("创建订单成功");
        bookRQResult.setResultCode("0");
        bookRQResult.setOrderId(orderEntity.getId().toString());
        return XmlUtils.toXML(bookRQResult);
    }


    /**
     * 保存订单
     * @param bookRQ
     * @param buySource
     */
    @Transactional
    public OrderEntity saveOrder(BookRQ bookRQ,Integer buySource,Integer orderType,Integer dtId,Integer storeId) {
        //订单主体
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setDtId(dtId);
        orderEntity.setDtStoreId(storeId);
        orderEntity.setBuySource(buySource);
        orderEntity.setOrderType(orderType);
        orderEntity.setBuyStatus(Constant.LocalOrdBuyStatus.Unpurchased.getValue());
        orderEntity.setOrderStatus(Constant.LocalOrderStatus.Paid.getValue());

        //每日价格
        List<DailyInfoEntity> dailyInfoEntities = Lists.newArrayList();
        //每日原始价格
        List<DailyOriInfoEntity> dailyOriInfoEntities = Lists.newArrayList();
        //每日折扣价格
        List<DailyDisInfoEntity> dailyDisInfoEntities = Lists.newArrayList();
        //入住人信息
        List<GuestEntity> guestEntitys = Lists.newArrayList();
        //发票信息
        InvoiceInfoEntity invoiceInfoEntity = null;
        //会员信息
        MemberInfoEntity memberInfoEntity = null;
        //礼包
        List<VoucherinfoEntity> voucherinfoEntities = Lists.newArrayList();
        //礼包
        PackEntity packEntity = null;
        List<PackInfoEntity> packInfoEntities = Lists.newArrayList();
        //商旅信息
        TravelInfoEntity travelInfoEntity = null;

        orderEntity.setDate(new Date());
        orderEntity.setOrderCode(Long.valueOf(bookRQ.getTaoBaoOrderId()));
        orderEntity.setShid(Long.valueOf(bookRQ.getTaoBaoHotelId()));
        orderEntity.setHotelCode(Long.valueOf(bookRQ.getHotelId()));
        orderEntity.setSrc(Long.valueOf(bookRQ.getTaoBaoRoomTypeId()));
        orderEntity.setRoomCode(Long.valueOf(bookRQ.getRoomTypeId()));
        orderEntity.setSrpc(Long.valueOf(bookRQ.getTaoBaoRatePlanId()));
        orderEntity.setRateplanCode(Long.valueOf(bookRQ.getRatePlanCode()));
        if (StringUtils.isNotBlank(bookRQ.getChannel())) {
            orderEntity.setPlantfrom(bookRQ.getChannel());
        }
        orderEntity.setPlanformGoodsId(Long.valueOf(bookRQ.getTaoBaoGid()));
        orderEntity.setCheckInDate(DateUtils.stringToDate(bookRQ.getCheckIn(), "yyyy-MM-dd"));
        orderEntity.setCheckOutDate(DateUtils.stringToDate(bookRQ.getCheckOut(), "yyyy-MM-dd"));
        orderEntity.setEarliestTime(DateUtils.stringToDate(bookRQ.getEarliestArriveTime(), "yyyy-MM-dd HH:mm:ss"));
        orderEntity.setLatestTime(DateUtils.stringToDate(bookRQ.getLatestArriveTime(), "yyyy-MM-dd HH:mm:ss"));
        orderEntity.setRoomNum(Integer.valueOf(bookRQ.getRoomNum()));
        orderEntity.setPerNum(Integer.valueOf(bookRQ.getOccupancy()));
        if (StringUtils.isNotBlank(bookRQ.getPriceType())) {
            orderEntity.setPriceType(Integer.valueOf(bookRQ.getPriceType()));
        }
        if (StringUtils.isNotBlank(bookRQ.getIsMorningBuy())) {
            orderEntity.setMorningRoom(Integer.valueOf(bookRQ.getIsMorningBuy()));
        }
        if (StringUtils.isNotBlank(bookRQ.getInventoryType())) {
            orderEntity.setInventoryType(Integer.valueOf(bookRQ.getInventoryType()));
        }
        orderEntity.setTotalPrice(Integer.valueOf(bookRQ.getTotalPrice()));
        if (StringUtils.isNotBlank(bookRQ.getOtherFee())) {
            orderEntity.setOtherFees(Integer.valueOf(bookRQ.getOtherFee()));
        }
        if (StringUtils.isNotBlank(bookRQ.getPaidPrice())) {
            orderEntity.setPayPrice(Integer.valueOf(bookRQ.getPaidPrice()));
        }
        if (StringUtils.isNotBlank(bookRQ.getTotalSellerPromotion())) {
            orderEntity.setReducedPrice(Integer.valueOf(bookRQ.getTotalSellerPromotion()));
        }
        orderEntity.setPaymentType(Integer.valueOf(bookRQ.getPaymentType()));
        orderEntity.setName(bookRQ.getContactName());
        orderEntity.setPhone(bookRQ.getContactTel());
        if (StringUtils.isNotBlank(bookRQ.getContactEmail())) {
            orderEntity.setEmail(bookRQ.getContactEmail());
        }
        //每日价格
        DailyInfoEntity dailyroomEntity = null;
        if (bookRQ.getDailyInfos() != null) {
            for (DailyInfo dailyInfo : bookRQ.getDailyInfos()) {
                dailyroomEntity = new DailyInfoEntity();
                dailyroomEntity.setOrderCode(orderEntity.getOrderCode());
                dailyroomEntity.setDate(DateUtils.stringToDate(dailyInfo.getDay(), "yyyy-MM-dd"));
                dailyroomEntity.setPrice(Long.valueOf(dailyInfo.getPrice()));
                if (StringUtils.isNotBlank(dailyInfo.getBreakFast())) {
                    dailyroomEntity.setBreakfastNum(Integer.valueOf(dailyInfo.getBreakFast()));
                }
                dailyInfoEntities.add(dailyroomEntity);
            }
        }
        if(dailyInfoEntities.size() > 0){
            dailyInfoService.saveBatch(dailyInfoEntities);
        }

        //每日原始价格
        DailyOriInfoEntity dailyOriInfoEntity = null;
        if (bookRQ.getSignMemberDailyInfos() != null) {
            for (DailyInfo dailyInfo : bookRQ.getSignMemberDailyInfos()) {
                dailyOriInfoEntity = new DailyOriInfoEntity();
                dailyOriInfoEntity.setOrderCode(orderEntity.getOrderCode());
                dailyOriInfoEntity.setDate(DateUtils.stringToDate(dailyInfo.getDay(), "yyyy-MM-dd"));
                dailyOriInfoEntity.setPrice(Long.valueOf(dailyInfo.getPrice()));
                if (StringUtils.isNotBlank(dailyInfo.getBreakFast())) {
                    dailyOriInfoEntity.setBreakfastNum(Integer.valueOf(dailyInfo.getBreakFast()));
                }
                dailyOriInfoEntities.add(dailyOriInfoEntity);
            }
        }
        if(dailyOriInfoEntities.size() > 0){
            dailyOriInfoService.saveBatch(dailyOriInfoEntities);
        }

        //每日折扣价格
        DailyDisInfoEntity dailyDisInfoEntity = null;
        if (bookRQ.getDisDailyInfos() != null) {
            for (DailyInfo dailyInfo : bookRQ.getDisDailyInfos()) {
                dailyDisInfoEntity = new DailyDisInfoEntity();
                dailyDisInfoEntity.setOrderCode(orderEntity.getOrderCode());
                dailyDisInfoEntity.setDate(DateUtils.stringToDate(dailyInfo.getDay(), "yyyy-MM-dd"));
                dailyDisInfoEntity.setPrice(Long.valueOf(dailyInfo.getPrice()));
                if (StringUtils.isNotBlank(dailyInfo.getBreakFast())) {
                    dailyDisInfoEntity.setBreakfastNum(Integer.valueOf(dailyInfo.getBreakFast()));
                }
                dailyDisInfoEntities.add(dailyDisInfoEntity);
            }
        }
        if(dailyDisInfoEntities.size() > 0){
            dailyDisInfoService.saveBatch(dailyDisInfoEntities);
        }

        //入住人信息
        GuestEntity guestEntity = null;
        if (bookRQ.getOrderGuests() != null) {
            for (OrderGuest guest : bookRQ.getOrderGuests()) {
                guestEntity = new GuestEntity();
                guestEntity.setOrderCode(orderEntity.getOrderCode());
                guestEntity.setName(guest.getName());
                if (StringUtils.isNotBlank(guest.getRoomPos())) {
                    guestEntity.setRoomPos(Integer.valueOf(guest.getRoomPos()));
                }
                if (StringUtils.isNotBlank(guest.getIdType())) {
                    guestEntity.setIdType(Integer.valueOf(guest.getIdType()));
                    guestEntity.setIdCode(guest.getIdCode());
                }
                guestEntitys.add(guestEntity);
            }
        }
        if(guestEntitys.size() > 0){
            guestService.saveBatch(guestEntitys);
        }

        if (StringUtils.isNotBlank(bookRQ.getComment())) {
            orderEntity.setNote(bookRQ.getComment());
        }
        //发票信息
        InvoiceInfo invoiceInfo = bookRQ.getInvoiceInfo();
        if (invoiceInfo != null) {
            invoiceInfoEntity = new InvoiceInfoEntity();
            invoiceInfoEntity.setOrderCode(orderEntity.getOrderCode());
            if (StringUtils.isNotBlank(invoiceInfo.getNeedInvoice())) {
                invoiceInfoEntity.setIsNeed(Integer.valueOf(invoiceInfo.getNeedInvoice()));
            }
            if (StringUtils.isNotBlank(invoiceInfo.getEarllyPrepare())) {
                invoiceInfoEntity.setIsPrepare(Integer.valueOf(invoiceInfo.getEarllyPrepare()));
            }
            if (StringUtils.isNotBlank(invoiceInfo.getSubmitTime())) {
                invoiceInfoEntity.setSubmTime(DateUtils.stringToDate(invoiceInfo.getSubmitTime(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (StringUtils.isNotBlank(invoiceInfo.getWantTime())) {
                invoiceInfoEntity.setWantTime(DateUtils.stringToDate(invoiceInfo.getWantTime(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (StringUtils.isNotBlank(invoiceInfo.getPostType())) {
                invoiceInfoEntity.setPostType(Integer.valueOf(invoiceInfo.getPostType()));
            }
            if (StringUtils.isNotBlank(invoiceInfo.getInvoiceType())) {
                invoiceInfoEntity.setType(Integer.valueOf(invoiceInfo.getInvoiceType()));
            }
            if (StringUtils.isNotBlank(invoiceInfo.getComment())) {
                invoiceInfoEntity.setItemComt(invoiceInfo.getComment());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getInvoiceTitle())) {
                invoiceInfoEntity.setTittle(invoiceInfo.getInvoiceTitle());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getCompanyTel())) {
                invoiceInfoEntity.setCompPhone(invoiceInfo.getCompanyTel());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getCompanyTax())) {
                invoiceInfoEntity.setTaxNo(invoiceInfo.getCompanyTax());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getRegisterAddress())) {
                invoiceInfoEntity.setCompAdd(invoiceInfo.getRegisterAddress());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getBank())) {
                invoiceInfoEntity.setBank(invoiceInfo.getBank());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getBankAccount())) {
                invoiceInfoEntity.setBankAcc(invoiceInfo.getBankAccount());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getReceiverAddress())) {
                invoiceInfoEntity.setPostAdd(invoiceInfo.getReceiverAddress());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getReceiverName())) {
                invoiceInfoEntity.setReceiverName(invoiceInfo.getReceiverName());
            }
            if (StringUtils.isNotBlank(invoiceInfo.getReceiverMobile())) {
                invoiceInfoEntity.setReceiverPhone(invoiceInfo.getReceiverMobile());
            }
        }
        if(invoiceInfoEntity != null){
            invoiceInfoService.save(invoiceInfoEntity);
        }

        //会员信息
        MemberInfo memberInfo = bookRQ.getMemberInfo();
        if (memberInfo != null && StringUtils.isNotBlank(memberInfo.getMemberName())) {
            memberInfoEntity = new MemberInfoEntity();
            memberInfoEntity.setOrderCode(orderEntity.getOrderCode());
            if (StringUtils.isNotBlank(memberInfo.getMemberName())) {
                memberInfoEntity.setName(memberInfo.getMemberName());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberFliggyNum())) {
                memberInfoEntity.setNum(memberInfo.getBookMemberFliggyNum());
            }
            if (StringUtils.isNotBlank(memberInfo.getMemberOutNum())) {
                memberInfoEntity.setOutNum(memberInfo.getMemberOutNum());
            }
            if (StringUtils.isNotBlank(memberInfo.getMemberPhone())) {
                memberInfoEntity.setPhone(memberInfo.getMemberPhone());
            }
            if (StringUtils.isNotBlank(memberInfo.getMemberEmail())) {
                memberInfoEntity.setEmail(memberInfo.getMemberEmail());
            }
            if (StringUtils.isNotBlank(memberInfo.getMemberFliggyLevel())) {
                memberInfoEntity.setLevel(memberInfo.getMemberFliggyLevel());
            }
            if (StringUtils.isNotBlank(memberInfo.getMemberOutLevel())) {
                memberInfoEntity.setOutLevel(memberInfo.getMemberOutLevel());
            }
            if (StringUtils.isNotBlank(memberInfo.getMemberIdCard())) {
                memberInfoEntity.setIdCard(memberInfo.getMemberIdCard());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberName())) {
                memberInfoEntity.setBookerName(memberInfo.getBookMemberName());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberFliggyNum())) {
                memberInfoEntity.setBookerNum(memberInfo.getBookMemberFliggyNum());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberOutNum())) {
                memberInfoEntity.setBookerOutNum(memberInfo.getBookMemberOutNum());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberPhone())) {
                memberInfoEntity.setBookerPhone(memberInfo.getBookMemberPhone());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberEmail())) {
                memberInfoEntity.setBookerEmail(memberInfo.getBookMemberEmail());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberFliggyLevel())) {
                memberInfoEntity.setBookerLevel(memberInfo.getBookMemberFliggyLevel());
            }
            if (StringUtils.isNotBlank(memberInfo.getBookMemberOutLevel())) {
                memberInfoEntity.setBookerOutLevel(memberInfo.getBookMemberOutLevel());
            }
        }
        if(memberInfoEntity != null){
            memberInfoService.save(memberInfoEntity);
        }

        if (StringUtils.isNotBlank(bookRQ.getAlipayTradeNo())) {
            orderEntity.setZfbId(bookRQ.getAlipayTradeNo());
        }
        //优惠信息
        VoucherinfoEntity voucherinfoEntity = null;
        if (bookRQ.getVoucherInfos() != null) {
            for (VoucherInfo voucherInfo : bookRQ.getVoucherInfos()) {
                voucherinfoEntity = new VoucherinfoEntity();
                voucherinfoEntity.setOrderCode(orderEntity.getOrderCode());
                if (StringUtils.isNotBlank(voucherInfo.getVoucherPomotionAmt())) {
                    voucherinfoEntity.setAmt(Integer.valueOf(voucherInfo.getVoucherPomotionAmt()));
                }
                if (StringUtils.isNotBlank(voucherInfo.getVoucherPomotionDesc())) {
                    voucherinfoEntity.setVoucDesc(voucherInfo.getVoucherPomotionDesc());
                }
                if (StringUtils.isNotBlank(voucherInfo.getVoucherRuleDesc())) {
                    voucherinfoEntity.setRuleDesc(voucherInfo.getVoucherRuleDesc());
                }
                if (StringUtils.isNotBlank(voucherInfo.getVoucherOutCode())) {
                    voucherinfoEntity.setOutCode(voucherInfo.getVoucherOutCode());
                }
                if (StringUtils.isNotBlank(voucherInfo.getVoucherTid())) {
                    voucherinfoEntity.setTid(voucherInfo.getVoucherTid());
                }
                if (StringUtils.isNotBlank(voucherInfo.getVoucherNum())) {
                    voucherinfoEntity.setVoucherNum(Integer.valueOf(voucherInfo.getVoucherNum()));
                }
                if (StringUtils.isNotBlank(voucherInfo.getPaidFee())) {
                    voucherinfoEntity.setPaidFee(Integer.valueOf(voucherInfo.getPaidFee()));
                }
                voucherinfoEntities.add(voucherinfoEntity);
            }
        }
        if(voucherinfoEntities.size() > 0){
            voucherinfoService.saveBatch(voucherinfoEntities);
        }
        //礼包关联订单
        PackageInfos packageInfos = bookRQ.getPackageInfos();
        PackInfoEntity packInfoEntity = null;
        if (packageInfos != null && StringUtils.isNotBlank(packageInfos.getDesp())) {
            packEntity = new PackEntity();
            packEntity.setOrderCode(orderEntity.getOrderCode());
            packEntity.setDesp(packageInfos.getDesp());
        }
        if(packEntity != null) {
            packService.save(packEntity);
        }
        //礼包项目
        if (packageInfos != null && packageInfos.getPackageInfo() != null) {
            for (PackageInfo packageInfo : packageInfos.getPackageInfo()) {
                packInfoEntity = new PackInfoEntity();
                packInfoEntity.setPackId(packEntity.getId());
                if (StringUtils.isNotBlank(packageInfo.getDimensionType())) {
                    packInfoEntity.setDimeType(packageInfo.getDimensionType());
                }
                if (StringUtils.isNotBlank(packageInfo.getQuantity())) {
                    packInfoEntity.setQuantity(Integer.valueOf(packageInfo.getQuantity()));
                }
                if (StringUtils.isNotBlank(packageInfo.getUnit())) {
                    packInfoEntity.setUnit(packageInfo.getUnit());
                }
                if (StringUtils.isNotBlank(packageInfo.getPackageType())) {
                    packInfoEntity.setPackType(packageInfo.getPackageType());
                }
                if (StringUtils.isNotBlank(packageInfo.getName())) {
                    packInfoEntity.setName(packageInfo.getName());
                }
                if (StringUtils.isNotBlank(packageInfo.getSubDesp())) {
                    packInfoEntity.setDesp(packageInfo.getSubDesp());
                }
                packInfoEntities.add(packInfoEntity);
            }
        }
        if(packInfoEntities.size() > 0){
            packInfoService.saveBatch(packInfoEntities);
        }
        //商旅信息
        if (bookRQ.getTravelInfo() != null) {
            TravelInfo travelInfo = bookRQ.getTravelInfo();
            travelInfoEntity = new TravelInfoEntity();
            travelInfoEntity.setOrderCode(orderEntity.getOrderCode());
            if (StringUtils.isNotBlank(travelInfo.getOrderType())) {
                travelInfoEntity.setOrdertype(Integer.valueOf(travelInfo.getOrderType()));
            }
            if (StringUtils.isNotBlank(travelInfo.getCompany())) {
                travelInfoEntity.setCompany(travelInfo.getCompany());
            }
        }
        if(travelInfoEntity != null){
            travelInfoService.save(travelInfoEntity);
        }
        if(StringUtils.isNotBlank(bookRQ.getOriginPaymentType())){
            orderEntity.setPaymentType(Integer.valueOf(bookRQ.getOriginPaymentType()));
        }

        orderService.save(orderEntity);
        return  orderEntity;
    }

    @Override
    public String paySuccessRQ(String xml) {
        PaySuccess paySuccess = XmlUtils.fromXML(xml,PaySuccess.class);
        PaySuccessResult paySuccessResult = new PaySuccessResult();
        paySuccessResult.setResultCode("0");
        paySuccessResult.setMessage("成功");
        if(paySuccess == null || paySuccess.getTaoBaoOrderId() == null){
            return  XmlUtils.toXML(paySuccessResult);
        }
        Long orderCode = paySuccess.getTaoBaoOrderId();
        OrderEntity orderEntity = orderService.sqlselectByOrderCode(orderCode);
        //自有数据如果查不到订单，则返回成功
        if (orderEntity==null){
            return  XmlUtils.toXML(paySuccessResult);
        }
        orderEntity.setOrderStatus(Constant.LocalOrderStatus.Paid.getValue());
        if(paySuccess.getPayment() != null) {
            orderEntity.setPayPrice(paySuccess.getPayment());
        }
        if(paySuccess.getAlipayTradeNo() != null) {
            orderEntity.setZfbId(paySuccess.getAlipayTradeNo());
        }
        orderService.updateById(orderEntity);
        return  XmlUtils.toXML(paySuccessResult);
    }

    /**
     * 查询订单状态
     * @param xml
     * @return
     */
    @Override
    public String queryStatusRQ(String xml) {
        QueryStatusRQRequest qsRQ =  XmlUtils.fromXML(xml,QueryStatusRQRequest.class);
        QueryStatusRQResult qsRQResult = new QueryStatusRQResult();
        //自有数据
        if (StringUtils.contains(qsRQ.getHotelId(),Constant.ChanelZy)){
            qsRQResult.setMessage("处理成功");
            qsRQResult.setResultCode("0");
            qsRQResult.setOrderId(qsRQ.getOrderId());
            return XmlUtils.toXML(qsRQResult);
        }
        String orderCode = qsRQ.getTaoBaoOrderId();
        OrderEntity orderEntity = orderService.sqlselectByOrderCode(Long.valueOf(orderCode));
        if(orderEntity == null){
            qsRQResult.setMessage("查询失败");
            qsRQResult.setResultCode("-302");
            qsRQResult.setOrderId("0");
            return XmlUtils.toXML(qsRQResult);
        }
        qsRQResult.setMessage("处理成功");
        qsRQResult.setResultCode("0");
        qsRQResult.setTaoBaoOrderId(orderCode);
        qsRQResult.setOrderId(orderEntity.getId().toString());
        Constant.LocalOrderStatus localOrderStatus = Constant.LocalOrderStatus.getLocalOrderStatusByValue(orderEntity.getOrderStatus());
        switch (localOrderStatus){
            case Unpaid:
                qsRQResult.setStatus(Constant.AliOrderStatus.Dealing.getValue().toString());
                break;
            case Paid:
                qsRQResult.setStatus(Constant.AliOrderStatus.Confirm.getValue().toString());
                break;
            case Delivered:
                qsRQResult.setStatus(Constant.AliOrderStatus.Confirm.getValue().toString());
                break;
            case ApplyRefund:
                qsRQResult.setStatus(Constant.AliOrderStatus.Confirm.getValue().toString());
                break;
            case Refund:
                qsRQResult.setStatus(Constant.AliOrderStatus.Cancel.getValue().toString());
                break;
            case Close:
                qsRQResult.setStatus(Constant.AliOrderStatus.Closed.getValue().toString());
                break;
        }
        qsRQResult.setTotalRoomPrice(orderEntity.getTotalPrice().toString());
        if(orderEntity.getOtherFees() != null) {
            qsRQResult.setOtherFee(orderEntity.getOtherFees().toString());
        }else {
            qsRQResult.setOtherFee("0");
        }
        return XmlUtils.toXML(qsRQResult);
    }

    /**
     * 申请退款通知
     * @param xml
     * @return
     */
    @Override
    public String orderRefundRQ(String xml) {
        OrderRefundRQ orderRefundRQ = XmlUtils.fromXML(xml,OrderRefundRQ.class);
        String orderCode = orderRefundRQ.getTaoBaoOrderId();
        CancelRQResult cancelRQResult = new CancelRQResult();
        cancelRQResult.setMessage("成功");
        cancelRQResult.setResultCode("0");
        if(StringUtils.isBlank(orderCode)){
            return XmlUtils.toXML(cancelRQResult);
        }
        OrderEntity orderEntity = orderService.sqlselectByOrderCode(Long.valueOf(orderCode));
        //查不到数据返回成功
        if (orderEntity==null){
            return XmlUtils.toXML(cancelRQResult);
        }
        cancelRQResult.setOrderId(orderEntity.getId().toString());
        Integer buySource = orderEntity.getBuySource();
        Constant.Channel channel = Constant.Channel.getChannelByValue(buySource);
        try{
            //自定义价格政策，需要手工取消
            switch (channel){
                case Manual:
                    orderEntity.setOrderStatus(Constant.LocalOrderStatus.ApplyRefund.getValue());
                    orderService.updateById(orderEntity);
                    break;
                case Ctrip:
                    ctripOrderService.cancel(orderEntity,orderRefundRQ.getAuthenticationToken().getUsername());
                    orderEntity.setOrderStatus(Constant.LocalOrderStatus.Refund.getValue());
                    orderService.updateById(orderEntity);
                case Mt:
                    mtOrderService.cancel(orderEntity,orderRefundRQ.getAuthenticationToken().getUsername());
                    orderEntity.setOrderStatus(Constant.LocalOrderStatus.Refund.getValue());
                    orderService.updateById(orderEntity);
                    break;
            }

        }catch (Exception ex){
            log.error(ex.toString());
        }
        return XmlUtils.toXML(cancelRQResult);
    }

    /**
     * 取消订单
     * @param xml
     * @return
     */
    @Override
    public String cancelRQ(String xml) {
        CancelRQ cancelRQ = XmlUtils.fromXML(xml, CancelRQ.class);
        Long orderCode = Long.valueOf(cancelRQ.getTaoBaoOrderId());
        OrderEntity orderEntity =  orderService.sqlselectByOrderCode(orderCode);

        //查不到数据为空则返回成功
        if (orderEntity==null){
            CancelRQResult cancelRQResult = new CancelRQResult();
            cancelRQResult.setOrderId(cancelRQ.getOrderId());
            cancelRQResult.setMessage("成功");
            cancelRQResult.setResultCode("0");
            return XmlUtils.toXML(cancelRQResult);
        }
        Integer buySource = orderEntity.getBuySource();
        Constant.Channel channel = Constant.Channel.getChannelByValue(buySource);
        String response = "";
        switch (channel){
            case Ctrip:
                response = ctripOrderService.cancel(orderEntity,cancelRQ.getAuthenticationToken().getUsername());
                break;
            case Mt:
                response = mtOrderService.cancel(orderEntity,cancelRQ.getAuthenticationToken().getUsername());
                break;
            case Manual:
                response = manualCancelOrder(orderEntity);
                break;
        }
        return response;
    }

    /**
     * 手工订单取消订单
     * @param orderEntity
     * @return
     */
    private String manualCancelOrder(OrderEntity orderEntity) {
        CancelRQResult cancelRQResult = new CancelRQResult();
        orderEntity.setOrderStatus(Constant.LocalOrderStatus.Refund.getValue());
        cancelRQResult.setMessage("成功");
        cancelRQResult.setResultCode("0");
        cancelRQResult.setOrderId(orderEntity.getId().toString());
        //更新采购信息
        orderService.updateById(orderEntity);
        return XmlUtils.toXML(cancelRQResult);
    }
}
